/**
 * 管理初始化
 */
var RoomProperty = {
    id: "RoomPropertyTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
RoomProperty.initColumn = function () {
    return [
        {field: 'selectItem', radio: false},
        // {title: '主键', field: 'id', visible: true, align: 'center', valign: 'middle'},
        {title: '房间资产名称', field: 'name', visible: true, align: 'center', valign: 'middle'}
    ];
};

/**
 * 检查是否选中
 */
RoomProperty.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        RoomProperty.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加
 */
RoomProperty.openAddRoomProperty = function () {
    var index = layer.open({
        type: 2,
        title: '添加',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/roomProperty/roomProperty_add'
    });
    this.layerIndex = index;
};

/**
 * 打开查看详情
 */
RoomProperty.openRoomPropertyDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '详情',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/roomProperty/roomProperty_update/' + RoomProperty.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 删除
 */
RoomProperty.delete = function () {
    if (this.check()) {
        var ajax = new $ax(Feng.ctxPath + "/roomProperty/delete", function (data) {
            Feng.success("删除成功!");
            RoomProperty.table.refresh();
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("roomPropertyId", this.seItem.id);
        ajax.start();
    }
};

/**
 * 查询列表
 */
RoomProperty.search = function () {
    var queryData = {};
    queryData['condition'] = $("#condition").val();
    RoomProperty.table.refresh({query: queryData});
};

//获取数据

var i = 0;
$('.dateBox').find(".list-group").each(function () {
    var value = $.trim($(this).find("#rent").text());
    if(value == '已出租'){
        $(this).find("#rent").css("background-color", 'rgb(50, 183, 92)');
    }
    console.log(value);
    $(this).click(function () {
        var item = $(this).attr("id");
        // console.log(item);
        gain(item);

    })
})

function gain(item) {
    $.ajax({
        type: 'GET',
        url: Feng.ctxPath + '/roomProperty/selectRoomByRoomId?roomId=' + item,
        dataType: 'json',
        cache: false,
        success: function (data) {
            $(".detail").find("div").attr('id', item);
            $(".detail").find("div").find("a").eq(0).find("h4").text(data['name']);
            $(".detail").find("div").find("a").eq(0).find("p").text(data['is_rent']);
            $(".detail").find("div").find("a").eq(0).find("p").css("background-color", "gray");
            if($.trim($(".detailContrast").text()) == '已出租'){
                console.log("chengg")
                $(".detailContrast").css("background-color", 'rgb(50, 183, 92)');
            }
            $(".detail").find("div").find("a").eq(1).find("h4").text("房间编码：" + data['buildCode']);
            var msg = data.recordList;
            // console.log(msg)
            if ($(".detail").find("div").attr('id', item) && msg.length != 0) {
                $(".payMent").html("");
                for (var i in msg) {
                    var html = '';
                    console.log(msg[i].payTime);
                    var payMentDate = msg[i].payTime;
                    var payAmount = msg[i].amount;
                    var payMentNow = new Date(payMentDate);
                    //格式化日，如果小于9，前面补0
                    var payMentDay = ("0" + payMentNow.getDate()).slice(-2);
                    //格式化月，如果小于9，前面补0
                    var payMentMonth = ("0" + (payMentNow.getMonth() + 1)).slice(-2);
                    //拼装完整日期格式
                    var payMent = payMentNow.getFullYear() + "-" + (payMentMonth) + "-" + (payMentDay);
                    html += `
                            <div><span>第${++i}次缴费: ${payMent}</span> (<i>￥${payAmount}</i> )</div>
                            `
                    $(".payMent").css("display", "block");
                    $(".payMent").append(html);
                }
            } else {
                $(".payMent").css("display", "none");
            }

            //房间详情显示费用的判断逻辑
            var fee1 = data['monthRent'];
            var fee2 = data['pledgeCash'];
            var text = '';
            if (!(fee1 == null)) {
                //如果有月租，显示月租
                text = '月租：' + fee1;
            } else if (!(fee2 == null)) {
                //否则，如果有押金显示押金
                text = '押金：' + fee2;
            } else {
                //否则显示空字符串
                text = '';
            }

            $(".detail").find("div").find("a").eq(1).find("p").text(text);

            //起租时间转换
            var detailStart = data['startDate'];
            var detailStart = getMyDate(detailStart);
            $(".detail").find("div").find("a").eq(2).find("p").text("起租时间：" + detailStart);

            //到期日期转换
            var detailEnd = data['endDate'];
            var detailEnd = getMyDate(detailEnd);
            var detailEndNum = parseInt(detailEnd.replace("-","").replace("-",""));
            $(".detail").find("div").find("a").eq(2).find("h4").text("到期时间：" + detailEnd);
            //获取当天时间进行判断
            var theSameDay = new Date();
            //格式化日，如果小于9，前面补0
            var sameDay = ("0" + theSameDay.getDate()).slice(-2);
            //格式化月，如果小于9，前面补0
            var sameMonth = ("0" + (theSameDay.getMonth() + 1)).slice(-2);
            //拼装完整日期格式
            var sameToday = parseInt(theSameDay.getFullYear() + (sameMonth) + (sameDay));
            if ((detailEndNum - sameToday) < 0) {
                $(".detail").find(".detailContrast").css("background-color", "red");
                $(".detail").find(".detailContrast").text("已过期")
            }
            if ((detailEndNum - sameToday) >= 0 && (detailEndNum - sameToday) <= 1) {
                $(".detail").find(".detailContrast").css("background-color", "skyblue");
                $(".detail").find(".detailContrast").text("已到期")
            }
            if ((detailEndNum - sameToday) > 1 && (detailEndNum - sameToday) <= 7) {
                $(".detail").find(".detailContrast").css("background-color", "orange");
                $(".detail").find(".detailContrast").text("快到期");
            }

        },
        error: function (data) {
            // console.log(data);
            console.log(data.responseText);
            console.log("失败");
        }
    });
}

function getMyDate(str){
    var oDate = new Date(str),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth()+1,
        oDay = oDate.getDate(),
        oHour = oDate.getHours(),
        oMin = oDate.getMinutes(),
        oSen = oDate.getSeconds(),
        oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay);//最后拼接时间
    return oTime;
};
//补0操作
function getzf(num){
    if(parseInt(num) < 10){
        num = '0'+num;
    }
    return num;
}

$(function () {
    var defaultColunms = RoomProperty.initColumn();
    var table = new BSTable(RoomProperty.id, "/roomProperty/list", defaultColunms);
    table.setPaginationType("client");
    RoomProperty.table = table.init();
    var obj = $(".detail").find("div").find("a");
    // console.log(obj.text());

    var now = new Date();
    //格式化日，如果小于9，前面补0
    var nowDay = ("0" + now.getDate()).slice(-2);
    //格式化月，如果小于9，前面补0
    var nowMonth = ("0" + (now.getMonth() + 1)).slice(-2);
    //拼装完整日期格式
    var today = parseInt(now.getFullYear() + (nowMonth) + (nowDay));

    $(".dateBox").find(".list-group").each(function () {
        var startDate = $(this).find(".startDate").attr("name");
        var startNow = getMyDate(startDate);
        $(this).find(".startDate").text(startNow);

        var endDate = $(this).find(".endDate").attr("name");
        var endNow = getMyDate(endDate);
        var endNum = parseInt(endNow.replace("-","").replace("-",""));
        $(this).find(".endDate").text(endNow);



        //进行日期判断，小于等于3天时显示快到期变红
        if ((endNum - today) < 0) {
            $(this).find(".contrast").css("background-color", "red");
            $(this).find(".contrast").text("已过期")
        }
        if ((endNum - today) >= 0 && (endNum - today) <= 1) {
            $(this).find(".contrast").css("background-color", "skyblue");
            $(this).find(".contrast").text("已到期")
        }
        if ( (endNum - today) > 1 && (endNum - today) <= 7) {
            $(this).find(".contrast").css("background-color", "orange");
            $(this).find(".contrast").text("快到期")

        }
        if ((endNum - today) <= 7) {
            //添加弹出框
            $(this).find(".startDate").append("<a class='btn-lg addpayTime' data-toggle='modal' data-target='#myModal' href = 'javascript:;'>添加缴费时间</a>");
            $(this).find(".startDate").find("a").css("float", "right")
            $(this).find(".btn-lg").css("padding", "0");
            $(this).find(".btn-lg").css("font-size", "16px");
        }

    })

    //页面详情页初始化起租时间和到期时间
    var detailStartDate = $(".detail").find(".startDate").attr("name");
    var detailStartNow = getMyDate(detailStartDate);
    console.log(detailStartNow)
    $(".detail").find(".startDate").text("起租日期: " + detailStartNow);

    var detailEndDate = $(".detail").find(".endDate").attr("name");
    var detailEndNow = getMyDate(detailEndDate);
    var detailEndNowNum = parseInt(detailEndNow.replace("-","").replace("-",""));
    $(".detail").find(".endDate").text("到期时间" + detailEndNow);

    if ((detailEndNowNum - today) < 0) {
        $(".detail").find(".detailContrast").css("background-color", "red");
        $(".detail").find(".detailContrast").text("已过期")
    }
    if ((detailEndNowNum - today) >= 0 && (detailEndNowNum - today) <= 1) {
        $(".detail").find(".detailContrast").css("background-color", "blue");
        $(".detail").find(".detailContrast").text("已到期")
    }
    if ((detailEndNowNum - today) >1 && (detailEndNowNum - today) <= 7) {
        $(".detail").find(".detailContrast").css("background-color", "orange");
        $(".detail").find(".detailContrast").text("快到期");
    }
    console.log($.trim($(".detailContrast").text()));
    if($.trim($(".detailContrast").text()) == '已出租'){
        // console.log("chengg")
        $(".detailContrast").css("background-color", 'rgb(50, 183, 92)');
    }
});
